#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>

#define N 310

using namespace std;

int ans[N][N];  int kill[N][N];
const int mv[4][2] = {{0 ,1}, {1, 0}, {-1, 0}, {0, -1}};

#define upd(x, y, t) kill[x][y] = min(kill[x][y], t);

void bfs(){ 
    queue < pair<int, int> > q;
    q.push(make_pair(0, 0));
    ans[0][0] = 0;
    while(!q.empty()){
        int dx = q.front().first; int dy = q.front().second;    q.pop();
        for(int i = 0; i < 4; i++){
            int xx = dx + mv[i][0];   int yy = dy +mv[i][1];
            if(xx < 0 || yy < 0 || ans[dx][dy]+1 >= kill[xx][yy] || ans[xx][yy] != -1 || xx > 301 || yy > 301){
                continue;
            }
            ans[xx][yy] = ans[dx][dy]+1;
            q.push(make_pair(xx, yy));
        }
    }
}

int main(){
    memset(ans, -1, sizeof(ans));
    memset(kill, 0x7f, sizeof(kill));
    int m;
    cin >> m;
    int x, y, t;
    for(int i = 1; i <= m; i++){
        scanf("%d%d%d", &x, &y, &t);
        upd(x, y, t);
        for(int j = 0; j < 4; j++){
            upd(x + mv[j][0], y + mv[j][1], t);
        }
    }
    bfs();
    int ANS = 100000;
    for(int i = 0; i < 310; i++){
        for(int j = 0; j < 310; j++){
            if(kill[i][j] > 1000 && ans[i][j] != -1){
                ANS = min(ANS, ans[i][j]);
            }
        }
    }
    if(ANS == 100000) cout << -1 << endl;
    else cout << ANS << endl;
    return 0;
}